package com.tarena.lbs.marketing.web.consumer;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.marketing.web.service.ActivityService;
import com.tarena.lbs.marketing.web.service.CouponService;
import com.tarena.lbs.marketing.web.service.UserCouponsService;
import com.tarena.lbs.pojo.basic.event.LocationEvent;
import com.tarena.lbs.pojo.marketing.param.UserCouponsParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class AutoMarketingConsumer {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserCouponsService userCouponsService;
    @StreamListener("marketing-store-location-input")
    public void storeLocation(LocationEvent event){
        log.info("自动营销服务接收到消息:{}",event);
        //1.调用活动业务 查询该事件消息中店铺 关联的所有 开启自动营销的活动
        List<ActivityPO> activities=activityService.getStoreActivities(event.getStoreId());
        //2.循环遍历活动数据 组织给用户领取优惠券的参数UserCouponsParam 调用领取功能
        if (activities!=null && activities.size()>0){
            //给用户尝试下发优惠券
            for (ActivityPO activity : activities) {
                //组织一个UserCouonsParam
                UserCouponsParam param=new UserCouponsParam();
                param.setActivityId(activity.getId());
                param.setCouponId(activity.getRewardCouponId());
                param.setShopId(event.getStoreId());
                param.setUserId(event.getUserId());
                try{
                    userCouponsService.receiveCoupon(param);
                }catch (BusinessException e){
                    log.error("领取优惠券出现业务问题",e);
                }catch(Throwable e){
                    log.error("领取优惠券出现系统问题",e);
                }
            }
        }
    }
}
